package at.cookieforensics;
import java.util.logging.FileHandler;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

/**
 * This class provides a logger for logging in a textfile
 * 
 * @author martin grottenthaler, markus stoeckler, lukas wabro
 * @version 1.0
 *
 */
public class CookieLogger {
	/** static CookieLogger instance */
	private static CookieLogger instance=null;
	/** static final Logger for logging */
	private static final Logger logger=Logger.getLogger(CookieLogger.class.getName());

	/**
	 * Constructor for the class Cookie Logger.
	 * <br>initialises the Logger
	 */
	private CookieLogger() {
		logger.setUseParentHandlers(false);
		try {
			MyFormatter formatter = new MyFormatter();
			Handler handler = new FileHandler("log.txt");
	        handler.setFormatter(formatter);
	        logger.addHandler(handler);
			logger.info("Started Logging");
		} catch (Exception e) {
			logger.severe("error while initialising Logger");
		}
	}
	/** 
	 * Gets an instance of the CookieLogger class.
	 * <br>Singelton Pattern
	 * @return instance of the CookieLogger class
	 */
	public static CookieLogger getInstance(){
		if(instance==null){
			instance= new CookieLogger();
		}
		return instance;
	}
	
	/**
	 * Gets the Logger for logging
	 * @return logger for logging
	 */
	public Logger getLogger(){
		return logger;
	}
}

/**
 * This class describes a new Formatter for the Logger
 * @author lukas wabro
 * @version 1.0
 *
 */
class MyFormatter extends Formatter {
    /**
     * Create a DateFormat to format the logger timestamp
     */
    private static final DateFormat df = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
    
    /**
     * Constructor for the MyFormatter class.
     * <br>not needed
     */
    MyFormatter(){
    }
    
    /**
     * Gets the formatted String
     * @param record LogRecord for ClassName, MethodName, etc.
     * @return String with the correct format
     */
    public String format(LogRecord record) {
        StringBuilder builder = new StringBuilder(1000);
        builder.append(df.format(new Date(record.getMillis()))).append(" - ");
        builder.append("[").append(record.getSourceClassName()).append(".");
        builder.append(record.getSourceMethodName()).append("] - ");
        builder.append("[").append(record.getLevel()).append("] - ");
        builder.append(formatMessage(record));
        builder.append("\n");
        return builder.toString();
    }

}